#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "kp_base_type.h"
#include "ebox_env_led.h"
#include "ebox_env_motor.h"

#define TASK_DELAY 200


/* 温湿度传感器处理任务，周期查询温度和湿度数据 */
void EnvShtTask(void)
{
    ShtIICInit();
	//osDelay(TASK_DELAY);
	SHT3XInit();
	osDelay(TASK_DELAY);
	
    /* 初始化变量 */
    float temperature = 0.0;
	float humidity = 0.0;
	static motor_speed_level motorSpeed = MOTOR_SPEED_LEVEL_0;
	
    while (1) {
		/* 查询温度和湿度数据 */
	    SHT3XReadMeasurementBuffer(&temperature, &humidity);
		//hi_watchdog_feed();
		printf("2000301532\r\n");
	    printf("temperature:%.2f, humidity:%.2f \r\n", temperature, humidity);
	    if (humidity > 80.0) {
			if (motorSpeed != MOTOR_SPEED_LEVEL_3) {
    			EnvMotorCtrl(MOTOR_SPEED_LEVEL_3);
				motorSpeed = MOTOR_SPEED_LEVEL_3;
    			printf("adjust motor speed to level 3 \r\n");
			}
	    } else if (humidity > 70.0) {
	        if (motorSpeed != MOTOR_SPEED_LEVEL_2) {
    			EnvMotorCtrl(MOTOR_SPEED_LEVEL_2);
				motorSpeed = MOTOR_SPEED_LEVEL_2;
    			printf("adjust motor speed to level 2 \r\n");
	        }
	    } else if (humidity > 60.0) {
			if (motorSpeed != MOTOR_SPEED_LEVEL_1) {
    			EnvMotorCtrl(MOTOR_SPEED_LEVEL_1);
				motorSpeed = MOTOR_SPEED_LEVEL_1;
    			printf("adjust motor speed to level 1 \r\n");
			}
	    } else {
	        if (motorSpeed != MOTOR_SPEED_LEVEL_0) {
    			EnvMotorCtrl(MOTOR_SPEED_LEVEL_0);
    			motorSpeed = MOTOR_SPEED_LEVEL_0;
    			printf("adjust motor speed to level 0 \r\n");
	        }
	    }
		osDelay(TASK_DELAY);
    }

    return;
}

void EnvSht30Sample(void)
{
    /* 各模块初始化 */
	EnvLedInit();
	EnvMotorInit();
	//ShtIICInit();
	//SHT3XInit();
	osDelay(TASK_DELAY);

	/* 设置线程属性 */
    osThreadAttr_t attr;
    attr.name = "EnvShtTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024 * 4;
    attr.priority = 20;
	
    /* 创建温湿度处理线程 */
    osThreadId_t threadIDSht = osThreadNew((osThreadFunc_t)EnvShtTask, NULL, &attr);
    if (threadIDSht == NULL)
    {
        printf("Falied to create EnvShtTask!\r\n");
    }
}

APP_FEATURE_INIT(EnvSht30Sample);
